using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

public class NetManager
{
    static Socket socket;

    static byte[] readBuff = new byte[1024];

    public delegate void MsgListener(string str);

    private static Dictionary<string, MsgListener> listeners = new Dictionary<string, MsgListener>();

    static List<string> msgList = new List<string>();
    /// <summary>
    /// 添加监听
    /// </summary>
    /// <param name="msgName">为网络协议名</param>
    /// <param name="listener">具体协议执行的函数回调</param>
    public static void AddListener(string msgName, MsgListener listener) => listeners[msgName] = listener;
    /// <summary>
    /// 获得描述
    /// </summary>
    public static string GetDesc()
    {
        if (socket == null)
            return "";
        if (!socket.Connected)
            return "";
        return socket.LocalEndPoint.ToString();

    }

    public static void Connect(string ip, int port)
    {
        //Socket
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //Connect
        socket.Connect(ip, port);
        //BeginReceive
        socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallBack, socket);
    }

    //

    private static void ReceiveCallBack(IAsyncResult ar)
    {
        try
        {

            Socket socket = (Socket)ar.AsyncState;
            int count = socket.EndReceive(ar);
            string recvStr = Encoding.Default.GetString(readBuff, 0, count);
            msgList.Add(recvStr);
            socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallBack, socket);
        }
        catch (SocketException e)
        {
            Debug.Log("Socket Receive Fail" + e.ToString());
        }
    }

    public static void Send(string sendStr)
    {
        if (socket == null) return;
        if (!socket.Connected) return;

        byte[] sendBytes = Encoding.Default.GetBytes(sendStr);
        socket.Send(sendBytes);

    }

    public static void Update()
    {
        if (msgList.Count <= 0)
        {
            return;
        }
        string msgStr = msgList[0];
        msgList.RemoveAt(0);
        string[] split = msgStr.Split("|");
        string msgName = split[0];
        string msgArgs = split[1];
        //监听回调
        if (listeners.ContainsKey(msgName))
        {
            listeners[msgName](msgArgs);
        }
    }
}
